//
//  XGSmallVideoPlayerViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/5/21.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import BMPlayer

class XGSmallVideoPlayerViewController: UIViewController
{
    init(currentIndex: Int, videoList: [XGSmallVideoModel])
    {
        self.currentIndex = currentIndex
        self.videoList = videoList
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "currentIndex")
    }
    
    // MARK: - 控制器生命周期方法
    override func loadView()
    {
        super.loadView()
        setUpUI()
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        DispatchQueue.main.async {
            self.tableView.scrollToRow(at: IndexPath(row: self.currentIndex, section: 0), at: .top, animated: false)
            self.addObserver(self, forKeyPath: "currentIndex", options: [.initial,.new,.old], context: nil)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
        
    // MARK: - 私有属性
    @objc dynamic private var currentIndex: Int = 0
    private var videoList: [XGSmallVideoModel]
    private lazy var backButton: UIButton = {
        let button = UIButton(imageName: "icon_titlebar_whiteback", highlightedImageName: "icon_titlebar_whiteback", target: self, action: #selector(backAction))
        return button
    }()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.xg_registerCell(cellType: XGSmallVideoPlayerCell.self)
        tableView.showsVerticalScrollIndicator = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .black
        return tableView
    }()
}

// MARK: - 数据源和代理

extension XGSmallVideoPlayerViewController: UITableViewDataSource,UITableViewDelegate
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return videoList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGSmallVideoPlayerCell
        cell.smallVideoModel = videoList[indexPath.item]
        return cell
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)
    {
        DispatchQueue.main.async {
            scrollView.panGestureRecognizer.isEnabled = false
            let offsetY = scrollView.panGestureRecognizer.translation(in: scrollView).y
            if offsetY < -100 && self.currentIndex < self.videoList.count - 1 {
                XGPrint("向下翻页")
                self.currentIndex += 1
            } else if (offsetY > 100 && self.currentIndex > 0) {
                XGPrint("向上翻页")
                self.currentIndex -= 1
            }
            
            UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut, animations: {
                self.tableView.scrollToRow(at: IndexPath(row: self.currentIndex, section: 0), at: .top, animated: false)
            }) { (_) in
                scrollView.panGestureRecognizer.isEnabled = true
            }
        }
    }
        
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
    {
        if keyPath != "currentIndex" {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }
        
        guard let urlString = videoList[currentIndex].main_mv_urls?.first?.url,
              let playerUrl = URL(string: urlString),
              let newCell = tableView.cellForRow(at: IndexPath(row: currentIndex, section: 0)) as? XGSmallVideoPlayerCell else {
            return
        }
        
        if let oldIndex = change?[NSKeyValueChangeKey.oldKey] as? Int,
            let oldCell = tableView.cellForRow(at: IndexPath(row: oldIndex, section: 0)) as? XGSmallVideoPlayerCell {
            oldCell.playerView.isPlaying ? oldCell.playerView.pause() : ()
        }
                
        newCell.playerView.setVideo(resource: BMPlayerResource(url: playerUrl))
    }
}

// MARK: - 私有扩展

private extension XGSmallVideoPlayerViewController
{
    func setUpUI() -> Void
    {
        view.backgroundColor = .black
        view.addSubview(tableView)
        view.addSubview(backButton)
        backButton.frame = CGRect(x: 30, y: TodayNews_StatusBar_Height, width: 40, height: 40)
        tableView.frame = CGRect(x: 0, y: -view.height, width: view.width, height: 3.0 * view.height)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.contentInset = UIEdgeInsets(top: view.height, left: 0, bottom: view.height, right: 0)
        tableView.rowHeight = view.height
    }
    
    @objc func backAction() -> Void
    {
        navigationController?.popViewController(animated: true)
    }
}
